package com.his.utils;

import com.his.entity.HisUser;
import com.his.entity.Patient;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * JWT工具类用于解析jwt
 * @author dawn
 */
public final class JWTUtil {

    private JWTUtil() {
    }

    /**
     * 生成token,使用私钥对数据进行加密生成jwt
     *
     * @param object：荷载
     * @param date：过期时间，单位分钟
     * @param priRsaPath：私钥的路径
     * @return 返回加密后的token
     */
    public static String generateToken(Object object, Integer date, String priRsaPath) throws Exception {
        String token = null;
        if(object instanceof HisUser){
            HisUser user= (HisUser) object;
            token = Jwts.builder().claim("id", user.getId())
                    .claim("name", user.getRealName())
                    .claim("roles", user.getRoles())
                    .setExpiration(DateTime.now().plusMinutes(date).toDate())
                    .signWith(SignatureAlgorithm.RS256, RsaUtils.getPrivateKey(priRsaPath)).compact();
        }else if(object instanceof Patient){
            Patient patient= (Patient) object;
            token = Jwts.builder().claim("id", patient.getId())
                    .claim("name", patient.getRealName())
                    .setExpiration(DateTime.now().plusMinutes(date).toDate())
                    .signWith(SignatureAlgorithm.RS256, RsaUtils.getPrivateKey(priRsaPath)).compact();
        }
        return token;
    }

    /**
     * 解析token
     *
     * @param token：要解析的token字符串
     * @param pubRsaPath：公钥路径
     * @return 返回加密后的对象可能是医院人员可能是病人
     */
    public static Object parserToken(String token, String pubRsaPath) throws Exception {
        Claims body = Jwts.parser().setSigningKey(RsaUtils.getPublicKey(pubRsaPath)).parseClaimsJws(token).getBody();
        Integer id = (Integer) body.get("id");
        List<String> roles = (List<String>) body.get("roles");
        if(StringUtils.isEmpty(roles)){
            Patient patient=new Patient();
            patient.setId(id);
            patient.setRealName((String)body.get("name"));
            return patient;
        }
        HisUser user = new HisUser();
        user.setId(id);
        user.setRealName((String) body.get("name"));
        user.setRoles(roles);
        return user;
    }
}
